package com.zbkj.crmeb.order.channel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.util.StringUtil;
import com.utils.jackyun.JackyunOpenHttpUtils;
import com.utils.jackyun.JkyProductUtil;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.JackyunOrderCancelRequest;
import com.zbkj.crmeb.order.request.JackyunOrderCreateRequest;
import com.zbkj.crmeb.order.request.JackyunOrderCreateRequest.TradeOrder;
import com.zbkj.crmeb.order.request.JackyunOrderCreateRequest.TradeOrderDetail;
import com.zbkj.crmeb.store.dao.PurchaseGoodsDao;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.PurchaseGoods;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.StoreOrderStatusService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class JkyStoreOrderServiceImpl extends AbstractStoreOrderService {
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    private StoreOrderFactory storeOrderFactory;
    @Resource
    private PurchaseGoodsDao purchaseGoodsDao;
    @Resource
    private JkyProductUtil jkyProductUtil;
    @Resource
    private StoreOrderStatusService storeOrderStatusService;
    
	@Value("${order.push.jky}")
	private boolean jkyPush;
	
    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
    	if(!jkyPush) {
            throw new CrmebException("吉客云订单推送状态未开启!");
    	}

        // 判断是否特殊商户订单(四个特殊商户)
        boolean jkyPushType = true;
        String shopName = "";
        switch (storeOrder.getMerId()){
            case 18:
            	shopName = "8F品牌专营店";
                break;
            case 30:
            	shopName = "8F时尚买手店";
                break;
//            case 41:
//            	shopName = "GMGB潮童馆";
//            	break;
            case 45:
            	shopName = "够购时尚海淘";
            	break;
            case 47:
            	shopName = "MM订货系统";
            	break;
            default:
            	jkyPushType = false;
            	shopName = "速云代理";
        }
        try {
			for (StoreOrderInfoVo info : orderInfoVoList) {
				JSONObject resultObj = new JSONObject();
				TradeOrder tradeOrder = new TradeOrder();
				tradeOrder.setTradeTime(storeOrder.getCreateTime());
				tradeOrder.setPayTime(storeOrder.getPayTime());
				// tradeOrder.setPayType(storeOrder.getPayType());
				if(storeOrder.getPayType().equals("weixin")){ //支付方式
					tradeOrder.setPayType((byte) 3);
				}else{
					tradeOrder.setPayType((byte) 6);
				}
				// 支付单号
				if(storeOrder.getIsChannel() == 1){ //小程序订单
					tradeOrder.setPayNo(storeOrder.getOutOrderId());
					tradeOrder.setCustomerPayNo(storeOrder.getOutOrderId());
				}else{
					tradeOrder.setPayNo(storeOrder.getPayNo());
					tradeOrder.setCustomerPayNo(storeOrder.getPayNo());
				}
				tradeOrder.setShopName(shopName);
				tradeOrder.setWarehouseCode("001");
				tradeOrder.setTradeType("1");
				tradeOrder.setReceiverName(storeOrder.getRealName());
				String[] phone = storeOrder.getUserPhone().split(" ");
				tradeOrder.setPhone(phone.length > 1 ? phone[1] : phone[0]);
				tradeOrder.setMobile(phone.length > 1 ? phone[1] : phone[0]);
//            tradeOrder.setCountry("中国");
				tradeOrder.setState(storeOrder.getProvince());
				tradeOrder.setCity(storeOrder.getCity());
				tradeOrder.setDistrict(storeOrder.getDistrict());
				tradeOrder.setAddress(storeOrder.getDetail());
				if (StringUtil.isNotEmpty(storeOrder.getIdCard())) {
					tradeOrder.setIdentityCardType("1");
					tradeOrder.setIdentityCardNo(storeOrder.getIdCard());
					tradeOrder.setIdentityCardName(storeOrder.getRealName());
				}
				if (Objects.nonNull(storeOrder.getSource()) && 9 != storeOrder.getSource()) {
					storeOrder.setPushOrderNo(info.getChildOrderNumber());
				}else
				{
					storeOrder.setPushOrderNo(info.getChildOrderNumber());
				}
				tradeOrder.setOnlineTradeNo(storeOrder.getOrderId() + "-" + storeOrder.getPushOrderNo());

				BigDecimal totalFee = BigDecimal.ZERO;
				BigDecimal postFee = BigDecimal.ZERO;
				BigDecimal taxFee = BigDecimal.ZERO;
				List<TradeOrderDetail> tradeOrderDetails = new ArrayList<TradeOrderDetail>();
				String barCode = info.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
				int isEur = info.getInfo().getProductInfo().getIsEurope();
				// barCode = barCode.substring(4, barCode.length()).split("-")[0];
				String suk = info.getInfo().getProductInfo().getAttrInfo().getSuk();
				String sourceSkuId = info.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
				if (sourceSkuId.startsWith(ProductTypeEnum.JKY.getCode() + "-")) {
					sourceSkuId = sourceSkuId.replaceFirst(ProductTypeEnum.JKY.getCode() + "-", "");
				} else {
					// 非吉客云商品则创建货品
					boolean b = jkyProductUtil.remotePushProductOne(info);
					//if(b) {
					// 目前不管货品创建状态
					if(!b) {
						log.info("--------------- 吉客云创建商品失败!!! 订单可能失败:{} ---------------", info.getInfo().getProductInfo().getId());
					}
					// barCode = info.getInfo().getProductInfo().getKeyword() + "-" + info.getInfo().getProductInfo().getId();
					sourceSkuId = info.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
//					} else {
//						barCode = "20220301001";
//						sourceSkuId = "2022030100111";
//						log.info("--------------- 创建商品失败!!!:{} ---------------", info.getInfo().getProductInfo().getId());
//					}
					
				}
//                BigDecimal otPrice = info.getInfo().getProductInfo().getAttrInfo().getSourceCost();
				BigDecimal count = BigDecimal.valueOf(info.getInfo().getCartNum());
//                BigDecimal sellPrice = otPrice.multiply(count);

				if (jkyPushType) {
					totalFee = totalFee.add(info.getPayPrice());
				} else {
					BigDecimal sourceCost = info.getInfo().getProductInfo().getSourceCost();
					sourceCost = null == sourceCost ? info.getInfo().getProductInfo().getAttrInfo().getSourceCost() : sourceCost;
					totalFee = totalFee.add(sourceCost);
				}
				postFee = postFee.add(info.getFirstPrice()).add(info.getSecondPrice());
				taxFee = taxFee.add(info.getTaxPrice());
				TradeOrderDetail tradeOrderDetail = new TradeOrderDetail();
//                tradeOrderDetail.setGoodsNo(barCode.substring(4, barCode.length()));
				tradeOrderDetail.setGoodsNo(barCode);
				tradeOrderDetail.setSpecName(suk);
				tradeOrderDetail.setBarcode(sourceSkuId);
				tradeOrderDetail.setUnit("件");
				tradeOrderDetail.setSellCount(count);
				if (jkyPushType) {
					tradeOrderDetail.setSellPrice(info.getPayPrice());
					tradeOrderDetail.setSellTotal(info.getPayPrice());
					// 终端支付金额
					tradeOrder.setFenxiaoprice(info.getPayPrice());
				} else {
					tradeOrderDetail.setSellPrice(info.getInfo().getProductInfo().getSourceCost());
					tradeOrderDetail.setSellTotal(info.getInfo().getProductInfo().getSourceCost());
					// 终端支付金额
					tradeOrder.setFenxiaoprice(info.getInfo().getProductInfo().getSourceCost());
				}
				tradeOrderDetails.add(tradeOrderDetail);

				if (jkyPushType) {
					// 采购信息改为吉客云
					info.getInfo().getProductInfo().setIsEurope(PurchaseOrderChannelTypeEnum.JKY.getCode());
					info.getInfo().getProductInfo().setSupplierName(PurchaseOrderChannelTypeEnum.JKY.getMsg());
				}
				tradeOrder.setTotalFee(totalFee);
				tradeOrder.setPostFee(postFee);
				tradeOrder.setReceivedPostFee(postFee);
				tradeOrder.setTaxFee(taxFee);
				tradeOrder.setPayment(totalFee);
				tradeOrder.setTradeOrderDetails(tradeOrderDetails);
				JackyunOrderCreateRequest request = new JackyunOrderCreateRequest();
				request.setTradeOrder(tradeOrder);

				String result = JackyunOpenHttpUtils.post("oms.trade.ordercreate", "v1.0", request);
				resultObj = JSONObject.parseObject(result);
	        	log.info("--------------- 推送至吉客云订单: {} 返回结果: {} ---------------", storeOrder.getId(), result);
	        	// 更新推送状态
	        	boolean b = false;
	        	// 是否是标识推送, 会影响到库存, 资金账户等
	        	boolean virtualPush = ProductTypeEnum.JKY != ProductTypeEnum.valueOf(isEur);
				if (200 == resultObj.getInteger("code")) {
					b = true;
					String outNo = resultObj.getJSONObject("result").getJSONObject("data").getJSONObject("tradeOrder").getString("tradeNo");
					// 新增采购单
					//2023.4.14 去掉采购单生成
//					storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.JKY.getCode());
					// 新增采购商品
//					storeOrderFactory.insertPurchaseGoods(Arrays.asList(info), storeOrder, true, "吉客云推送: 成功", outNo, virtualPush);
				} else {
//					storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.JKY.getCode());
//					storeOrderFactory.insertPurchaseGoods(Arrays.asList(info), storeOrder, false, resultObj.getString("msg"), null, virtualPush);
				}

	        	StoreOrder storeOrderUpdate = new StoreOrder();
	        	storeOrderUpdate.setId(storeOrder.getId());
        		storeOrderUpdate.setPushJkyStatus(b ? "1" : "2");
                storeOrderDao.updateById(storeOrderUpdate);
			}
            
            return CommonResult.success();
        } catch (Exception e) {
            log.info("--------------- 请求吉客云创建订单失败结果: {} ---------------", e);
        }

//		StoreOrder storeOrderUpdate = new StoreOrder();
//		storeOrderUpdate.setId(storeOrder.getId());
//		storeOrderUpdate.setPushStatus(2);
//		storeOrderUpdate.setPushMessage("吉客云推送:" + resultObj.getString("msg"));
//        storeOrderDao.updateById(storeOrderUpdate);
        return CommonResult.success();
//        return CommonResult.failed(resultObj.getString("msg"));
    }

    /**
     * 订单取消
     */
    @Override
    @Async("taskExecutor")
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
    	if(!jkyPush) {
    		return null;
    	}
    	
		try {
			List<PurchaseGoods> purchaseGoodsList = purchaseGoodsDao.selectList(Wrappers.<PurchaseGoods>lambdaQuery()
					.eq(PurchaseGoods::getStoreOrderId, storeOrder.getOrderId())
					.eq(PurchaseGoods::getPushType, 2)
					);
			List<String> tradeNos = purchaseGoodsList.stream().map(obj -> obj.getChannelOrderSn())
					.collect(Collectors.toList());
			JackyunOrderCancelRequest request = new JackyunOrderCancelRequest();
			request.setCancelReason("订单取消");
			request.setTradeNos(tradeNos);

			String result = JackyunOpenHttpUtils.post("oms.trade.ordercancel", "v1.0", request);
			log.info("--------------- 请求吉客云取消订单: {} 结果: {} ---------------", storeOrder.getOrderId(), result);
			JSONObject resultObj = JSONObject.parseObject(result);
			if (200 == resultObj.getInteger("code")) {
				return CommonResult.success();
			}
		} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
        return null;
    }

	@Override
	public CommonResult<Object> getOrderInfo(String channelOrderSn) {
		return null;
	}

}
